package org.gikolet.ch2.android.io;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringEscapeUtils;
import org.gikolet.ch2.data.Res;
import org.gikolet.ch2.io.Parser;
import org.gikolet.util.Tuple.Tuple2;

public class Ch2ResPAF implements Parser<Tuple2<Res, String>> {

	private static final Pattern RES_PTN = Pattern
			.compile("^(.*?)<>(.*?)<> ?(.*?)( ID:(\\S+))?( BE:(\\S+))?<>(.*?) ?<>(.*?)$");

	private static final Pattern HTML_TAG_BR_PTN = Pattern.compile(" ?<br> ?",
			Pattern.CASE_INSENSITIVE);

	private static final Pattern HTML_TAG_PTN = Pattern.compile("<.+?>",
			Pattern.CASE_INSENSITIVE);

	public String format(Tuple2<Res, String> res) throws IOException {
		return null;
	}

	public String format(List<Tuple2<Res, String>> ts) throws IOException {
		return null;
	}

	public Tuple2<Res, String> parse(String line) throws IOException {
		Matcher matcher = RES_PTN.matcher(line);

		if (!matcher.find()) {
			throw new IOException("Format is invalid. [" + line + "]");
		}

		Res r = new Res();
		r.setName(matcher.group(1));
		r.setMail(matcher.group(2));
		r.setDateString(matcher.group(3));
		r.setId(matcher.group(5));
		r.setBe(matcher.group(7));
		r.setBody(matcher.group(8));

		r.setBody(HTML_TAG_BR_PTN.matcher(r.getBody()).replaceAll("\n"));

		r.setName(HTML_TAG_PTN.matcher(r.getName()).replaceAll(""));
		r.setBody(HTML_TAG_PTN.matcher(r.getBody()).replaceAll(""));

		r.setName(StringEscapeUtils.unescapeHtml4(r.getName()));
		r.setMail(StringEscapeUtils.unescapeHtml4(r.getMail()));
		r.setDateString(StringEscapeUtils.unescapeHtml4(r.getDateString()));
		r.setId(StringEscapeUtils.unescapeHtml4(r.getId()));
		r.setBe(StringEscapeUtils.unescapeHtml4(r.getBe()));
		r.setBody(StringEscapeUtils.unescapeHtml4(r.getBody()));

		String subject = matcher.group(9);

		return new Tuple2<Res, String>(r, subject);
	}
}
